package com.wiseMen.weixin.utils;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.sword.lang.HttpUtils;

import com.alibaba.fastjson.JSONObject;
import com.wiseMen.platform.utils.RequestUtils;
import com.wiseMen.weixin.user.WxUserEntity;

public class SessionUtils {
	
	private static final Logger logger = Logger.getLogger(SessionUtils.class);

	public static  void setOpenId(String openId){
		RequestUtils.getHttpSession().setAttribute("WX_OPENID", openId);
	}
	
	public static String getOpenId(){
		return (String) RequestUtils.getHttpSession().getAttribute("WX_OPENID");
	}
	
	public static void setUser(WxUserEntity user){
		RequestUtils.getHttpSession().setAttribute("WX_USER", user);
	}
	
	public static WxUserEntity getUser(){
		WxUserEntity user = (WxUserEntity) RequestUtils.getHttpSession().getAttribute("WX_USER");
		return user;
	}
	
	private static final String getOpenIdUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxdbc0699fe6ce34fa&secret=5ffd534977de2853ae0a83376f1718e1&grant_type=authorization_code&code=";
    
    /**
     * 根据code（验证码）重新获取openId,并设入session中
     * 返回 openID
     */
    public static final String refurbishOpenId(String code){
    	String openId = null;
		try {
			String url = getOpenIdUrl + code;
			String jsonString = HttpUtils.post(url);
			if(StringUtils.isNotBlank(jsonString)){
				JSONObject jsonObject = JSONObject.parseObject(jsonString);
				if (jsonObject.containsKey("openid")) {
					openId = jsonObject.getString("openid");
					setOpenId(openId);
				}
			}
		}catch (Exception e) {
			logger.error(e);
		}
		return openId;
    }
}
